package com.gzhryc.shared_device.oem.h5.agent.mng.controllers.cdcz;

import com.gzhryc.common.ClassTools;
import com.gzhryc.common.MatrixToImageWriter;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.config.PropertyTools;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.cdcz.code.dao.db.ChargeSocket;
import com.gzhryc.shared_device.cdcz.code.dao.db.ChargeSocketSlaveDevice;
import com.gzhryc.shared_device.cdcz.code.dao.db.ChargeSocketSlot;
import com.gzhryc.shared_device.cdcz.code.dao.enums.ChargeSocketEnum;
import com.gzhryc.shared_device.cdcz.code.services.ChargeSocketService;
import com.gzhryc.shared_device.cdcz.code.services.ChargeSocketSlaveDeviceService;
import com.gzhryc.shared_device.cdcz.code.services.ChargeSocketSlotService;
import com.gzhryc.shared_device.cdcz.code.services.dto.ChargeSocketSearch;
import com.gzhryc.shared_device.cdcz.core.CDCZConstants;
import com.gzhryc.shared_device.common.device.dao.db.Device;
import com.gzhryc.shared_device.common.device.dao.db.DeviceType;
import com.gzhryc.shared_device.common.device.dao.db.DeviceTypeFunc;
import com.gzhryc.shared_device.common.device.services.DeviceService;
import com.gzhryc.shared_device.common.device.services.DeviceTypeFuncService;
import com.gzhryc.shared_device.common.device.services.DeviceTypeService;
import com.gzhryc.shared_device.iot.code.dao.db.IOTServerNode;
import com.gzhryc.shared_device.iot.code.services.IOTServerNodeService;
import com.gzhryc.shared_device.oem.code.device.EDeviceFunCode;
import com.gzhryc.shared_device.oem.code.user.dao.db.User;
import com.gzhryc.shared_device.oem.h5.agent.mng.WebConstants;
import com.gzhryc.shared_device.oem.h5.agent.mng.dto.cdcz.ChargeSocketData;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ChargeSocketController {

    static Logger log = Logger.getLogger(ChargeSocketController.class);

    @Route("/cdcz/device/list.html")
    public String list(HttpServletRequest request) {
        request.setAttribute("stateList", ChargeSocketEnum.State.values());
        return "/cdcz/device/list.html";
    }

    @Route(value = "/cdcz/device/list.data")
    public ListResult<ChargeSocketData> listData(HttpServletRequest request) {
        ListResult<ChargeSocketData> result = new ListResult<>(DtoConstants.NULL_DATA,"暂无数据");
        ChargeSocketSearch search = WebUtils.getParameter(request, ChargeSocketSearch.class);
        Integer pageNo = WebUtils.getInteger(request, "page", 1);
        Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if (loginUser != null) {
            search.setUserId(loginUser.getId());

            result.getBody().setTotal(ChargeSocketService.self().countJoinBySearch(search));
            List<ChargeSocket> chargeSocketsList = ChargeSocketService.self().findJoinBySearch(search, pageNo, pageLimit);
            if (chargeSocketsList != null && chargeSocketsList.size() > 0) {
                result.setCode(DtoConstants.SUCCESS, null);
                result.getBody().setData(new ArrayList<>());

                for (ChargeSocket chargeSocket : chargeSocketsList) {
                    ChargeSocketData item = ClassTools.copy(new ChargeSocketData(), chargeSocket);
                    IOTServerNode serverNode = IOTServerNodeService.self().getById(chargeSocket.getIotNodeId());
                    if (serverNode != null) {
                        item.setIotNodeName(serverNode.getName());
                    } else if (chargeSocket.getIotNodeId() != null) {
                        item.setIotNodeName(chargeSocket.getIotNodeId().toString());
                    }
                    result.getBody().getData().add(item);
                }
            }
        }
        return result;
    }

    @Route("/cdcz/device/add.html")
    public String add(HttpServletRequest request) {
        List<DeviceType> deviceTypeList = DeviceTypeService.self().findAll();
        request.setAttribute("deviceTypeList",deviceTypeList);
        List<IOTServerNode> iotNodeList = IOTServerNodeService.self().findAllUnable();;
        request.setAttribute("iotNodeList",iotNodeList);
        return "/cdcz/device/edit.html";
    }

    @Route(value = { "/cdcz/device/add.do" })
    public AjaxResult doAdd(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "新增充电插座主机失败");
        ChargeSocket chargeSocket = WebUtils.getParameter(request, ChargeSocket.class);
        try {
            DeviceType deviceType = DeviceTypeService.self().getById(chargeSocket.getDeviceTypeId());
            if(deviceType == null){
                result.setMsg("设备类型不存在");
                return result;
            }

            DeviceTypeFunc deviceTypeFunc = DeviceTypeFuncService.self()
                    .getByKeys(chargeSocket.getDeviceTypeId(), EDeviceFunCode.CDCZ.index());
            if(deviceTypeFunc == null){
                result.setMsg("设备类型不存在此功能");
                return result;
            }
            chargeSocket.setDeviceTypeName(deviceType.getName());
            chargeSocket.setProtocolType(deviceTypeFunc.getProtocolType());
            if(ChargeSocketService.self().add(chargeSocket)){
                result.setCode(DtoConstants.SUCCESS,null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route("/cdcz/device/info.html")
    public String info(HttpServletRequest request) {
        String deviceSn = WebUtils.getString(request,"deviceSn");
        if(StringTools.isNotBlank(deviceSn)){
            User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
            if (loginUser != null) {
                Device device = DeviceService.self().getByDeviceSn(deviceSn);
                if (device != null && device.getUserId() != null && device.getUserId().equals(loginUser.getId())) {
                    request.setAttribute("device", device);

                    ChargeSocket chargeSocket = ChargeSocketService.self().getJoinByDeviceSn(deviceSn);
                    if (chargeSocket != null) {
                        WebUtils.setAttribute(request, chargeSocket);

                        if (CDCZConstants.ProtocolTypeV2.equals(chargeSocket.getProtocolType())) {
                            return "/cdcz/device/v2/info.html";
                        }
                    }
                }
            }
        }
        return "/cdcz/device/info.html";
    }

    @Route(value = "/cdcz/device/slot/list.data")
    public ListResult<ChargeSocketSlot> slotListData(HttpServletRequest request) {
        ListResult<ChargeSocketSlot> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        String deviceSn = WebUtils.getString(request,"deviceSn");
        if(StringTools.isNotBlank(deviceSn)) {
            User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
            if (loginUser != null) {
                Device device = DeviceService.self().getByDeviceSn(deviceSn);
                if (device != null && device.getUserId() != null && device.getUserId().equals(loginUser.getId())) {
                    result.getBody().setTotal(ChargeSocketSlotService.self().countByDeviceSn(deviceSn));
                    result.getBody().setData(ChargeSocketSlotService.self().findByDeviceSn(deviceSn));

                    if (result.getBody().getData() != null && result.getBody().getData().size() > 0) {
                        result.setCode(DtoConstants.SUCCESS, null);
                    }
                }
            }
        }
        return result;
    }

    @Route(value = "/cdcz/device/slave_device/list.data")
    public ListResult<ChargeSocketSlaveDevice> slaveDeviceListData(HttpServletRequest request) {
        ListResult<ChargeSocketSlaveDevice> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        String deviceSn = WebUtils.getString(request,"deviceSn");
        if(StringTools.isNotBlank(deviceSn)) {
            User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
            if (loginUser != null) {
                Device device = DeviceService.self().getByDeviceSn(deviceSn);
                if (device != null && device.getUserId() != null && device.getUserId().equals(loginUser.getId())) {
                    result.getBody().setData(ChargeSocketSlaveDeviceService.self().findByMainDeviceSn(deviceSn));

                    if (result.getBody().getData() != null && result.getBody().getData().size() > 0) {
                        result.setCode(DtoConstants.SUCCESS, null);
                    }
                }
            }
        }
        return result;
    }

    @Route(value = { "/cdcz/device/qrcode.html" })
    public String qrcode(HttpServletRequest request) {
        String deviceSn = WebUtils.getString(request, "deviceSn");
        if (StringUtils.isNotBlank(deviceSn)) {
            ChargeSocket chargeSocket = ChargeSocketService.self().getByDeviceSn(deviceSn);
            if (chargeSocket != null) {
                String httpDomain = PropertyTools.get().getString("httpDomain");
                String url = httpDomain + "/dev/cdcz/" + chargeSocket.getDeviceSn();
                request.setAttribute("url", url);
            }
        }
        return "/cdcz/device/qrcode.html";
    }

    @Route(value = { "/cdcz/device/qrcode.jpg" })
    public void qrcodeImg(HttpServletRequest request, HttpServletResponse response) {
        String deviceSn = WebUtils.getString(request, "deviceSn");
        if (StringUtils.isNotBlank(deviceSn)) {
            ChargeSocket chargeSocket = ChargeSocketService.self().getByDeviceSn(deviceSn);
            if (chargeSocket != null) {
                try {
                    String httpDomain = PropertyTools.get().getString("httpDomain");
                    String url = httpDomain + "/dev/cdcz/" + chargeSocket.getDeviceSn();
                    WebUtils.exportJPEG(response);
                    MatrixToImageWriter.writeToStream(url, 400, 300, "jpeg", response.getOutputStream());
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    }

    @Route(value = { "/cdcz/device/del.do" })
    public AjaxResult doDel(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "删除充电插座主机失败");
        String deviceSn = WebUtils.getString(request,"deviceSn");
        if(StringTools.isNotBlank(deviceSn)) {
            User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
            if (loginUser != null) {
                Device device = DeviceService.self().getByDeviceSn(deviceSn);
                if (device != null && device.getUserId() != null && device.getUserId().equals(loginUser.getId())) {

                }else {
                    result.setMsg("无权限操作");
                }
            }
        }
        return result;
    }

}
